#include "HttpResponse.h"
#define ResHeaderSize 16
struct HttpResponse *httpResponseInit()
{
    struct HttpResponse *response = (struct HttpResponse *)malloc(sizeof(struct HttpResponse));
    response->headerNum = 0;
    int size = sizeof(struct ResponseHeader) * ResHeaderSize;
    response->headers = (struct ResponseHeader *)malloc(size);
    response->httpStatusCode = Unknow;
    // 初始化数组
    bzero(response->headers,size);
    bzero(response->statusMsg,sizeof(response->statusMsg));
    bzero(response->filename,sizeof(response->filename));
    // 函数指针 回调函数
    response->sendDataFunc = NULL;
    return response;
    
}

void HttpResponseestory(struct HttpResponse* httpResponse)
{
    if(httpResponse!=NULL)
    {
        free(httpResponse->headers);
        free(httpResponse);
    }
}
// 添加响应头

void addResponseHeader(struct HttpResponse* httpResponse,const char* key,const char* value)
{
    Debug("addResponseHeader start");
    if(httpResponse == NULL || key==NULL||value ==NULL)
    {
        return;
    }
    //C 语言指针不能直接进行赋值操作
    strcpy(httpResponse->headers[httpResponse->headerNum].key,key);
    Debug("响应头1 %s",httpResponse->headers[httpResponse->headerNum].key);
    strcpy(httpResponse->headers[httpResponse->headerNum].value,value);
    Debug("响应头1 %s",httpResponse->headers[httpResponse->headerNum].value);
    httpResponse->headerNum++;
    Debug("addResponseHeader end");
}

void httpResponsePrepareMsg(struct HttpResponse* httpResponse,struct Buffer* sendbuffer,int socket)
{
    // 状态行
    // 响应头
    // 空行
    // 回复数据
    char tmp[1024]={0};
    sprintf(tmp,"HTTP/1.1 %d %s\r\n",httpResponse->httpStatusCode,httpResponse->statusMsg);
    bufferAppendString(sendbuffer,tmp);

    // 响应头
    for(int i =0;i<httpResponse->headerNum;i++)
    {
        sprintf(tmp,"%s: %s\r\n",httpResponse->headers[i].key,httpResponse->headers[i].value);
        bufferAppendString(sendbuffer,tmp);
    }

    // 空行
    bufferAppendString(sendbuffer,"\r\n");
    // 先把上面部分的先发送
    
#ifndef MSG_SEND_AUTO // 这是ifndef 表示没有定义这个宏，这个代码是有效的 定义了就是无效的
    bufferSendData(sendbuffer,socket);
#endif
    // 回复的数据
    httpResponse->sendDataFunc(httpResponse->filename,sendbuffer,socket);
}